package com.cy.pj.sys.service.impl;

import com.cy.pj.common.annotation.RequiredLog;
import com.cy.pj.common.annotation.RequiredTime;
import com.cy.pj.sys.dao.SysLogDao;
import com.cy.pj.sys.pojo.SysLog;
import com.cy.pj.sys.service.SysLogService;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 用户日志业务规范的实现
 */
@Transactional(readOnly = false,
               timeout = 60,
               rollbackFor = Throwable.class,
               isolation = Isolation.REPEATABLE_READ)
@Service
public class SysLogServiceImpl implements SysLogService {
    //@Autowired
    private SysLogDao sysLogDao;

    public SysLogServiceImpl(SysLogDao sysLogDao) {
        this.sysLogDao = sysLogDao;
    }

    //@RequiredLog(operation = "新增日志")
    /**@Asunc 注解时，方法时没有返回值的，如果要加返回值，要使用future<object>标识返回值，然后return new AsyncResult(这里写参数)*/
    @Async //@Async注解描述的方法为一个异步切入点，这个方法执行时底层会在新的线程中进行调用
    @Override
    public void saveLog(SysLog sysLog) {
        System.out.println("saveLog:"+Thread.currentThread().getName());
        try { Thread.sleep(10000); }catch (Exception e){}
        //try { TimeUnit.SECONDS.sleep(10); }catch (Exception e){}

        sysLogDao.insertLog(sysLog);
    }


    @Transactional  //此注解描述方法时，这个方法为一个事务切入点方法
    //@RequiredLog(operation = "删除日志")
    @Override
    public int deleteById(Long... ids) {
        for (int i = 0; i < ids.length; i++) {
            if(i==1){
                //这里抛出异常时如何让已删除的数据回滚
                throw new RuntimeException("删除失败");
            }
            sysLogDao.deleteById(ids[i]);
        }
        return 10;
    }


    @RequiredLog(operation = "查询日志")
    @Override
    public SysLog findById(Long id) {
        SysLog sysLog = sysLogDao.selectById(id);
        if(sysLog==null){
            throw new RuntimeException("没有找到对应的记录");
        }
        return sysLog;
    }

    @Transactional(readOnly = true)
    @RequiredTime
    //@RequiredLog(operation = "查询日志")
    @Override
    public List<SysLog> findLogs(SysLog sysLog) {
        System.out.println("findLogs:"+Thread.currentThread().getName());
        List<SysLog> list = sysLogDao.selectLogs(sysLog);
        return list;
    }
}
